package com.shop.listener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionScanner implements HttpSessionListener,ServletContextListener {
	//包装线程安全的集合类
	private List<HttpSession> list = Collections.synchronizedList(new ArrayList<HttpSession>());
	private Object lock = new Object();
	
	public void contextInitialized(ServletContextEvent sce){
		//添加一个定时任务
		Timer timer = new Timer();
		// 定时器任务：每隔30秒就扫描一次集合：
		//是否有Session对象超时，若超时就会被处理（删除）
		//1. task执行的任务，2. 0 延迟时间 ， 3. 30秒扫描一次
		timer.schedule(new MyTask(list, lock),0, 30*1000);
	}
	
	
	//创建session加入list , 登录之后 session.setAtt
	 public void sessionCreated(HttpSessionEvent se){
		 System.out.println("创建session===" + se.getSession().getId()+"="+new Date());
		 HttpSession session = se.getSession();
		 synchronized (lock) {
		     list.add(session);	
		}
	 }
	 public void sessionDestroyed(HttpSessionEvent se){
		 System.out.println("销毁session===" + se.getSession().getId()+"="+new Date());
	 }
}
class MyTask extends TimerTask{
	private List<HttpSession> list;
	private Object lock;
	
	public MyTask(List<HttpSession> list, Object lock) {
		super();
		this.list = list;
		this.lock = lock;
	}

	@Override
	public void run() {
		System.out.println("11session.size="+ list.size()+ "==执行定时器==="+new Date());
		synchronized (lock) {
		    ListIterator<HttpSession> listIterator = list.listIterator();
		    while(listIterator.hasNext()){
		    	HttpSession session = listIterator.next();
		    	//判断时间间隔
		    	long time=System.currentTimeMillis() - session.getLastAccessedTime();
		    	if(  time > 30000  ){
		    		session.invalidate();//让session销毁
		    		listIterator.remove();//从集合移除
		    	}
		    }
		}
		System.out.println("22session.size="+ list.size()+ "==执行定时器==="+new Date());
	}
	
}
